<?php

namespace Lettral\LetterBundle\Controller;

use Doctrine\ORM\Query;

use Lettral\Helpers\StringUtils;

use Lettral\Latex\LatexGenerator;

use Lettral\UserBundle\Form\Type\UserPersonnalInfoForm;
use Lettral\LetterBundle\Form\LetterTypeForm;

use Lettral\Helpers\ResponseCreator;

use Lettral\Helpers\ConstraintViolationListExtended;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use FOS\UserBundle\Model\UserManagerInterface;
use Lettral\LetterBundle\Form\LetterForm;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use \Symfony\Component\HttpFoundation\Response;

use Lettral\Helpers;

class LetterController extends Controller
{
	
	/**
	 * Avant de créer sa lettre, choix du type de lettre, du modèle, etc.
	 * Non utilisé
	 */
	public function chooseAction() {
		
		if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
			throw new AccessDeniedException();
		}
		
		$form = $this->container->get('form.factory')->create(new LetterTypeForm());
		$request = $this->container->get('request');
		
		if ($request->getMethod() == 'POST')
		{
			$form->bindRequest($request);
			$letterType = $form->getData();
			
			$validator = $this->get('validator');
			$errors = $validator->validate($letterType);
			
			if (count($errors) == 0 && ($letterType->getTypeDest() == 'perso' || $letterType->getTypeDest() == 'pro')) {
				$url = $this->get('router')->generate('letter_letter_add_typed', array('typeDest' => $letterType->getTypeDest()));
				return ResponseCreator::getUrl($url);
			}
		}
		
		return $this->container->get('templating')->renderResponse('LettralLetterBundle:Letter:choose.html.twig',
			array('form' => $form->createView()));
	}
	
    public function addAction($numLetter = null, $generate = true)
    {
    	
    	$em = $this->container->get('doctrine.orm.entity_manager');
    	
        if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
            throw new AccessDeniedException();
        }
        
        $user = $this->get('security.context')->getToken()->getUser();        
        
        $letter = null;
        if (isset($numLetter)) {
        	$letter = $em->find('LettralLetterBundle:Lettre', $numLetter);
        	if ($letter == null || $letter->getUser()->getId() != $user->getId())
        		throw new NotFoundHttpException();
        }
        else {    
        	$letter = New \Lettral\LetterBundle\Entity\Lettre();   	
        	$letter->setSign($user->getPrenom()." ".$user->getNom());
        	$letter->setLieuEcriture($user->getVille());
        	$letter->setTypeDest(0);
        }        
        
        $form = $this->container->get('form.factory')->create(new LetterForm());
        $form->setData($letter);
        $profileForm = $this->container->get('form.factory')->create(new UserPersonnalInfoForm());
        $profileForm->setData($user);

        $request = $this->container->get('request');

        if ($request->getMethod() == 'POST') 
        {
            $form->bindRequest($request);            
            
            // traitement des différentes dates
            $now = new \DateTime("now");
            $letter->setDateCreation($now);
            $letter->setDateDerModif($now);
            $letter->setDateGeneration($now);
            if ($letter->getDateEcriture()->format('Ymd') < $now->format('Ymd'))
            	$letter->setDateEcriture($now);	

            // validation
            $validator = $this->get('validator');
            $errors = $validator->validate($letter);
			
            if (count($errors) == 0) 
            {   
             	$letter->setUser($user);
             	
             	if ($generate == "true") {
             		$em->persist($letter);
             		$em->flush();
             		$lg = new LatexGenerator();
	                $lg->generateCommands($letter);  
	                
	                if ($lg->generatePdf()) {
	                	$letter->setStatut(2);
	                	$em->persist($letter);
	                	$em->flush();
	                	return ResponseCreator::getSuccess($letter->getNumLettre());
	                } else {
	                	$letter->setStatut(3);
	                	$em->persist($letter);
	                	$em->flush();
	                	return ResponseCreator::getError("generation");
	                }
             	}
             	else {
             		$letter->setStatut(1);
             		$em->persist($letter);
             		$em->flush();
             		return ResponseCreator::getSuccess($letter->getNumLettre());
             	}             
            }
			else 
			{
				return ResponseCreator::getErrorList($errors);
			}
        }
        
        return $this->container->get('templating')->renderResponse('LettralLetterBundle:Letter:add.html.twig', 
                array('form' => $form->createView(), 'profileForm' => $profileForm->createView(), 'numLetter' => $letter->getNumLettre()));
    }
    
    /**
     * Supprimer une lettre
     * @param unknown_type $numLetter
     * @throws NotFoundHttpException
     * @throws AccessDeniedException
     */
    public function deleteAction($numLetter) {
    	
    	$em = $this->container->get('doctrine.orm.entity_manager');
  		$user = $this->get('security.context')->getToken()->getUser();
  		$letter = $em->find('LettralLetterBundle:Lettre', $numLetter);
  		
  		if ($letter == null)
  			throw new NotFoundHttpException();
   		
   		if ($letter->getUser()->getId() != $user->getId())
   			throw new AccessDeniedException();
   		
   		$id = $letter->getNumLettre();
   		
   		$em->remove($letter);
   		$em->flush();
    	
    	return ResponseCreator::getSuccess($id);
    }
    
    /**
     * Supprimer plusieurs lettres
     * @param unknown_type $numLetter
     * @throws NotFoundHttpException
     * @throws AccessDeniedException
     */
    public function multipleDeletesAction() {
    
    	$em = $this->container->get('doctrine.orm.entity_manager');
    	$user = $this->get('security.context')->getToken()->getUser();

    	if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
    		throw new AccessDeniedException();
    	}
    	
    	$request = $this->container->get('request');
    	$numLetters = $request->request->get('ids');
    	
    	$qb = $em->createQueryBuilder();
    	$qb ->add('select', 'letter.numLettre')
    		->add('from', 'LettralLetterBundle:Lettre letter')
    		->add('where', 'letter.user = :userId')->setParameter('userId', $user->getId())
    		->andWhere('letter.numLettre IN (:numLetters)')->setParameter('numLetters', $numLetters); 
   		$letters = $qb->getQuery()->getResult();
    
		if (count($letters) == count($numLetters)) {
			$qb = $em->createQueryBuilder();
			$qb	->delete('LettralLetterBundle:Lettre', 'letter')
				->andWhere('letter.numLettre IN (:numLetters)')->setParameter('numLetters', $numLetters);
			$qb->getQuery()->getResult();
			$em->flush();
			return ResponseCreator::getSuccess();
		}
    
		return ResponseCreator::getSuccess('no');
    }
    
  	/**
  	 * Télécharger une lettre
  	 * @param int $numLettre identifiant de la lettre
  	 */
  	public function downloadAction($numLettre) {
    	
  		$em = $this->container->get('doctrine.orm.entity_manager');
  		$user = $this->get('security.context')->getToken()->getUser();
  		$letter = $em->find('LettralLetterBundle:Lettre', $numLettre);
  		
  		if ($letter == null)
  			throw new NotFoundHttpException();
   		
  		if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
  			throw new AccessDeniedException();
  		}
   		
   		if ($letter->getUser()->getId() != $user->getId())
   			throw new AccessDeniedException();
   		
   		$filePath = LatexGenerator::checkGeneratedLetter($letter);
		
   		if (!$filePath)
   			throw new NotFoundHttpException();
   		
   		$fileName = StringUtils::formatLetterFilename($letter);
   		return ResponseCreator::getPdf($filePath, $fileName);
    }
    
    /**
     * Affiche une lettre dans une fancybox (unused)
     * @param unknown_type $numLettre
     */
    public function showPdfAction($numLettre) {
    
    	return $this->container->get('templating')->renderResponse('LettralLetterBundle:Letter:showPdf.html.twig', 
                array('numLettre' => $numLettre));
    }
    
    /**
     * Voir une lettre avec le plugin pdf du navigateur
     * @param int $numLettre identifiant de la lettre
     */
    public function showAction($numLettre) {
    
    	$em = $this->container->get('doctrine.orm.entity_manager');
    	$user = $this->get('security.context')->getToken()->getUser();
    	$letter = $em->find('LettralLetterBundle:Lettre', $numLettre);
    
    	if ($letter == null)
    	throw new NotFoundHttpException();
    	
    	if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
    		throw new AccessDeniedException();
    	}
    
    	if ($letter->getUser()->getId() != $user->getId())
    	throw new NotFoundHttpException();
    
    	$filePath = LatexGenerator::checkGeneratedLetter($letter);
    
    	if (!$filePath)
    	throw new NotFoundHttpException();
    
    	$fileName = StringUtils::formatLetterFilename($letter);
    	return ResponseCreator::showPdf($filePath, $fileName);
    }
    
    public function listAction($status = null, $start = null, $nb = null) {
    	
    	$em = $this->container->get('doctrine.orm.entity_manager');
    	$user = $this->get('security.context')->getToken()->getUser();
    	
    	if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
    		throw new AccessDeniedException();
    	}
    	
    	$qb = $em->createQueryBuilder();
    	$qb->add('select', 'letter.numLettre, letter.sujet, letter.nomDest, letter.compNomDest1, letter.dateDerModif, letter.statut') 
    		  ->add('from', 'LettralLetterBundle:Lettre letter');
    	is_int($status) ? $qb->add('where', 'letter.statut = :status')->setParameter('status', $status) : null;
    	$qb->add('where', 'letter.user = :userId')->setParameter('userId', $user->getId());
    	$qb->add('orderBy', 'letter.dateDerModif DESC');
    	if (intval($nb) == 0) {
    		$qb->setMaxResults(20);
    		$nb = 20;
    	} else {
    		$qb->setMaxResults($nb);
    	}
    	$qb->setFirstResult(intval($start));
    	$letters = $qb->getQuery()->getResult();
    	
    	$hasPrev;
    	if ($start == 0 || $start == null) {
    		$hasPrev = 1;
    	} else {
    		$hasPrev = 0;
    	}
    	
    	$qb = $em->createQueryBuilder();
    	$qb->add('select', 'count(letter.numLettre) as nb')->add('from', 'LettralLetterBundle:Lettre letter');
    	$qb->add('where', 'letter.user = :userId')->setParameter('userId', $user->getId());
    	$nbLetters = $qb->getQuery()->getSingleResult();
  		
    	$hasNext = 1;
    	if ($nbLetters['nb'] > ($start + $nb)) {
    		$hasNext = 0;
    	}
    	
    	return $this->container->get('templating')->renderResponse('LettralLetterBundle:Letter:list.html.twig',
    		array('letters' => $letters, 'hasPrev' => $hasPrev, 'hasNext' => $hasNext));
    }
}
